package cn.xo68.boot.auth.core.web;

import cn.xo68.boot.auth.core.domain.Oauth2Principal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * shiro方法参数解析器
 * @author wuxie
 * @date 2018-8-14
 */
public class ShiroMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return Oauth2Principal.class.equals(parameter.getParameterType()) || Subject.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        if(Oauth2Principal.class.equals(parameter.getParameterType())){
            if(subject.isAuthenticated()){
                return subject.getPrincipal();
            }else {
                return null;
            }
        }else {
            return subject;
        }
    }
}
